'use strict';

/**
 * @name 通用编辑组件
 * @description 通用编辑组件
 * @author ZYF
 */
angular.module('metalabOperationApp').factory('MetaEdit', ['$rootScope', 'MetaRemind', 'MetaConstants', 'MetaUtils', 'MetaResources', function($rootScope, MetaRemind, MetaConstants, MetaUtils, MetaResources) {
    var metaEdit = {};

    /**
     * @name 初始化编辑控制器
     * @description scope为$scope, stateParams为$stateParams, type为模块名称, 例如demand, technology等等, embed为内嵌的字段名称
     */
    metaEdit.initEditModule = function(scope, stateParams, type, embed) {
        //初始化其他通用组件
        scope.openModel = MetaUtils.openModel;
        //action表示需要改变的键，例如rank推荐，online上保密，state状态
        scope.changeControlState = function(action, data) {
            var passData = {};
            var innerType = type;
            var method = "save";
            switch (action) {
                case 'rank':
                    passData[action] = scope.editCtrl.data.rank = (scope.editCtrl.data.rank === 0 ? 1 : 0);
                    break;
                case 'online':
                    passData[action] = scope.editCtrl.data.online = (scope.editCtrl.data.online === true ? false : true);
                    break;
                case 'talentOnline':
                    passData.online = scope.editCtrl.data.talent.online = (scope.editCtrl.data.talent.online === true ? false : true);
                    innerType = "talent";
                    break;
                case 'createTalent':
                    passData.online = true;
                    innerType = "talent";
                    method = 'create';
                    break;
                case 'updateRole':
                    passData.role = 'admin';
                    method = 'updateRole';
                    break;
                default:
                    break;
            }
            MetaResources[innerType][method]({
                'id': type==="talent"?scope.editCtrl.data.userId:stateParams.id
            }, passData, function() {
                MetaRemind.success("恭喜", "修改成功");
                metaEdit.syncData(scope.editCtrl, type);
            });
        };
        //重置方法
        scope.reset = function() {
            scope.editCtrl.data = angular.copy(scope.editCtrl.backup);
        };
        //根据不同类型的模块，添加不同的方法
        if (type === 'demand' || type === 'technology') {
            //重置负责人
            scope.resetAssign = function() {
                if (scope.editCtrl.data.leader) {
                    $rootScope.leaderCandidate = scope.editCtrl.data.leader.name;
                    $rootScope.leaderCandidateId = scope.editCtrl.data.leader.id;
                    if ((scope.editCtrl.data.leaderId === scope.editCtrl.data.publisherId) && type === 'demand') {
                        scope.editCtrl.type = "申请人";
                    } else {
                        scope.editCtrl.type = "合伙人";
                    }
                } else {
                    scope.editCtrl.type = "";
                }
                if (scope.editCtrl.data.projectManager) {
                    scope.editCtrl.manager = scope.editCtrl.data.projectManager.name;
                } else {
                    scope.editCtrl.manager = "";
                }
            };
            //更新候选人状况
            scope.updateLeader = function() {
                if (scope.editCtrl.type === "申请人") {
                    $rootScope.leaderCandidateId = scope.editCtrl.data.publisherId;
                    $rootScope.leaderCandidate = scope.editCtrl.data.publisher.name;
                }
            };
        } else if (type === 'process') {
            //进程状态对比
            scope.editCtrl.stateCompare = {
                '审核通过': 0,
                '联系沟通': 1,
                '邀请对接': 2,
                '线下对接': 3,
                '提交合同': 4,
                '确认签约': 5,
                '已完成': 6
            };
            //重置负责人
            scope.resetAssign = function() {
                if (scope.editCtrl.data.demand.leader) {
                    $rootScope.leaderCandidate = scope.editCtrl.data.demand.leader.name;
                    $rootScope.leaderCandidateId = scope.editCtrl.data.demand.leader.id;
                    if (scope.editCtrl.data.demand.leaderId === scope.editCtrl.data.demand.publisherId) {
                        scope.editCtrl.type = "申请人";
                    } else {
                        scope.editCtrl.type = "合伙人";
                    }
                } else {
                    scope.editCtrl.type = "";
                }
                if (scope.editCtrl.data.demand.projectManager) {
                    scope.editCtrl.manager = scope.editCtrl.data.demand.projectManager.name;
                } else {
                    scope.editCtrl.manager = "";
                }
            };
            //更新候选人状况
            scope.updateLeader = function() {
                if (scope.editCtrl.type === "申请人") {
                    $rootScope.leaderCandidateId = scope.editCtrl.data.demand.publisherId;
                    $rootScope.leaderCandidate = scope.editCtrl.data.demand.publisher.name;
                }
            };
        } else if (type === 'user') {
            scope.spaceStatus = 0;
            scope.money = {
                'float': 0,
                'cause': ''
            };
            scope.spaceChange = function(index) {
                scope.spaceStatus = index;
            };
            //重置负责人
            scope.resetAssign = function() {
                $rootScope.referenceCandidate = scope.editCtrl.backupreferenceName;
                $rootScope.referenceCandidateId = scope.editCtrl.backupreferenceId;
            };
            //保存商务金
            scope.saveMoney = function() {
                if (scope.money.float === 0 || scope.money.cause === '') {
                    MetaRemind.warn("提示", "请输入金额和原因");
                } else {
                    var data = angular.copy(scope.money);
                    data.userId = stateParams.id;
                    data.operatorId = '_self';
                    MetaResources.user.saveMoney({
                            '_embed': 'operator'
                        }, data,
                        function(data) {
                            MetaRemind.success("恭喜", "添加成功");
                            scope.editMoneyCtrl.data.unshift(data);
                        },
                        function(error) {
                            MetaRemind.serverError(error);
                        });
                }
            };
            //重置商务金
            scope.resetMoney = function() {
                scope.money.float = 0;
                scope.money.cause = '';
            };
        } else if (type === 'talent') {
          scope.spaceStatus = (stateParams.tab === undefined?0:stateParams.tab);
        }
        //将项目负责人设置清空
        $rootScope.leaderCandidate = "暂无";
        $rootScope.leaderCandidateId = "";
        //获取数据
        var queryParams = {
            'id': stateParams.id,
            '_embed': embed
        };
        //如果是需求或者技术，则调用updateData，如果是其他的，直接调用getPreProcess
        switch (type) {
            case 'demand':
            case 'technology':
                MetaResources[type].get(queryParams,
                    function(data) {
                        metaEdit.updateData(scope, data, type);
                    },
                    function(error) {
                        MetaRemind.serverError(error);
                    });
                break;
            case 'process':
                MetaResources[type].get(queryParams,
                    function(data) {
                        metaEdit.getPreProcess(scope.editCtrl, data, type);
                    },
                    function(error) {
                        MetaRemind.serverError(error);
                    });
                break;
            case 'user':
                var needProcess = {
                    'get': {
                        'queryParams': queryParams,
                        'editCtrl': scope.editCtrl,
                        'type': type
                    },
                    'getMoney': {
                        'queryParams': {
                            'user_id': stateParams.id,
                            '_embed': 'operator',
                            '_sort': '-created_at'
                        },
                        'editCtrl': scope.editMoneyCtrl,
                        'type': 'moneyList'
                    },
                    'getCollect': {
                        'queryParams': {
                            'user_id': stateParams.id,
                            '_embed': 'target,target.user',
                            '_sort': '-created_at'
                        },
                        'editCtrl': scope.editCollectCtrl,
                        'type': 'collectList'
                    }
                };
                angular.forEach(needProcess, function(value, key) {
                    MetaResources[type][key](
                        value.queryParams,
                        function(data) {
                            metaEdit.getPreProcess(value.editCtrl, data, value.type);
                        },
                        function(error) {
                            MetaRemind.serverError(error);
                        }
                    );
                });
                break;
            case 'talent':
                var needProcess2 = {
                    'get': {
                        'queryParams': queryParams,
                        'editCtrl': scope.editCtrl,
                        'type': type
                    },
                    'queryAreas': {
                        'queryParams': {
                            'id': stateParams.id,
                            '_sort': '-created_at'
                        },
                        'editCtrl': scope.editAreasCtrl,
                        'type': 'areasList'
                    },
                    'queryAchievements': {
                        'queryParams': {
                            'id': stateParams.id,
                            '_sort': '-created_at'
                        },
                        'editCtrl': scope.editAchievementsCtrl,
                        'type': 'achievementsList'
                    }
                };
                angular.forEach(needProcess2, function(value, key) {
                    MetaResources[type][key](
                        value.queryParams,
                        function(data) {
                            metaEdit.getPreProcess(value.editCtrl, data, value.type);
                        },
                        function(error) {
                            MetaRemind.serverError(error);
                        }
                    );
                });
                break;
            default:
                break;
        }
    };

    /**
     * @name 需求和技术获取数据后调用的方法
     * @description 因为需求和技术有线上数据和原始数据两部分，所以要对两个数据分别进行预处理
     */
    metaEdit.updateData = function(scope, data, type) {
        metaEdit.getPreProcess(scope.editCtrl, data, type);
        metaEdit.getPreProcess(scope.editCtrl, data.other, type);
        scope.isInit = false;
        scope.changeInit = function() {
            scope.isInit = !scope.isInit;
            if (scope.isInit) {
                //需要保存一下编辑的状态
                scope.editCtrl.online = angular.copy(scope.editCtrl.data);
                scope.editCtrl.data = angular.copy(scope.editCtrl.original);
            } else {
                scope.editCtrl.data = angular.copy(scope.editCtrl.online);
            }
        };
    };

    /**
     * @name 获取数据后的预处理
     * @description 与处理多选项、范围值以及调整右边控件区的属性
     */
    metaEdit.getPreProcess = function(editCtrl, editData, editType) {
        //partnerInfo可能为undefined
        if (editType === 'user' && editData.partnerInfo === undefined) {
            editData.partnerInfo = {};
            editData.partnerInfo.areas = [];
        }
        //遍历所有属性，预处理多选项、范围值
        angular.forEach(editData, function(value, key) {
            switch (key) {
                // case 'areas':
                //     for (var i = 0; i < value.length; i++) {
                //       if (value[i].indexOf(":")==-1) {
                //         var temp = {};
                //         temp.firstArea = value[i];
                //         temp.secondArea = '其他';
                //         temp.areaValue = value[i] + ":其他";
                //         editData[key][i] = temp;
                //       } else {
                //         var temp = {};
                //         temp.firstArea = value[i].substr(0,value[i].indexOf(":"));
                //         temp.secondArea = value[i].substr(0,value[i].indexOf(":")+1);
                //         temp.areaValue = value[i];
                //         editData[key][i] = temp;
                //       }
                //     }
                //     break;
                case 'areas':
                    editData.area_choice = {
                        'area01': false,
                        'area02': false,
                        'area03': false,
                        'area04': false,
                        'area05': false,
                        'area06': false
                    };
                    for (var i = 0; i < editData.areas.length; i++) {
                        editData.area_choice[MetaConstants.map.areas[MetaConstants.map.areas.indexOf(editData.areas[i]) + MetaConstants.map.areas.length / 2]] = true;
                    }
                    break;
                case 'cover':
                    editData['coverImg'] = {};
                    editData['coverImg']['link'] = editData.cover;
                    break;
                case 'partnerInfo':
                    var processValue = angular.copy(value);
                    if (processValue && processValue.areas) {
                        processValue = processValue.areas;
                    }
                    editData.area_choice = {
                        'area01': false,
                        'area02': false,
                        'area03': false,
                        'area04': false,
                        'area05': false,
                        'area06': false
                    };
                    if (processValue) {
                        for (var i = 0; i < processValue.length; i++) {
                            editData.area_choice[MetaConstants.map.areas[MetaConstants.map.areas.indexOf(processValue[i]) + MetaConstants.map.areas.length / 2]] = true;
                        }
                    }
                    break;
                case 'cooperationWays':
                    editData.cooperationForm_choice = {
                        'cooperationForm01': false,
                        'cooperationForm02': false,
                        'cooperationForm03': false,
                        'cooperationForm04': false,
                        'cooperationForm05': false
                    };
                    if (value) {
                        for (var j = 0; j < value.length; j++) {
                            editData.cooperationForm_choice[MetaConstants.map.cooperations[MetaConstants.map.cooperations.indexOf(value[j]) + MetaConstants.map.cooperations.length / 2]] = true;
                        }
                    }
                    break;
                case 'willingToFollow':
                    editData[key] = value + ""; //转化成字符串，如果是true的话，则候选项中添加申请人的选项
                    if (editData[key] === "true" && editType === "demand" && editData.version === 'online') {
                        editCtrl.typeOptions = ['合伙人', '申请人'];
                    }
                    break;
                case 'patentState':
                case 'proprietary':
                    editData[key] = value + "";
                    break;
                case 'leader':
                    editData.way_choice = {
                        'area01': false,
                        'area02': false,
                        'area03': false,
                        'area04': false,
                        'area05': false,
                        'area06': false
                    };
                    if (value && value.partnerInfo && value.partnerInfo.areas) {
                        for (var k = 0; k < value.partnerInfo.areas.length; k++) {
                            editData.way_choice[MetaConstants.map.areas[MetaConstants.map.areas.indexOf(value.partnerInfo.areas[k]) + MetaConstants.map.areas.length / 2]] = true;
                        }
                    }
                    break;
                case 'researchPeriod':
                    if (!value) {
                        value = [0, 0];
                    } else if (value.length === 1) {
                        value[1] = 0;
                    }
                    break;
                default:
                    break;
            }
        });

        //设置右侧控件状态
        switch (editType) {
            //如果是需求或者方案，那需要判断所有委派操作是否已经完成
            case 'demand':
            case 'technology':
                if (editData.version === 'online') {
                    //负责人选项
                    if (!editCtrl.typeOptions) {
                        editCtrl.typeOptions = ['合伙人'];
                    }
                    //是否委派以及是否审核
                    editData.isAssigned = (editData.leader === undefined || editData.leader === null || editData.projectManager === undefined || editData.projectManager === null) ? false : true;
                    editData.hasVerified = (editData.verified === undefined || editData.verified === null) ? false : true;
                    //判断是否有负责人，有的话设置好，并判断是否与发布者一致
                    if (editData.leader) {
                        $rootScope.leaderCandidate = editData.leader.name;
                        $rootScope.leaderCandidateId = editData.leader.id;
                        if (editData.leaderId === editData.publisherId && editType === "demand") {
                            editCtrl.type = "申请人";
                        } else {
                            editCtrl.type = "合伙人";
                        }
                    }
                    //判断是否有项目经理，有的话设置好
                    if (editData.projectManager) {
                        editCtrl.manager = editData.projectManager.name;
                    }
                    //将线上数据赋值给显示数据、线上数据、备份数据
                    editCtrl.data = angular.copy(editData);
                    editCtrl.online = angular.copy(editData);
                    editCtrl.backup = angular.copy(editData);
                } else {
                    //对origin部分数据进行修改，避免切换的时候，将右边的控件区域的数据也重置为原始版本
                    angular.forEach(editData, function(value, key) {
                        switch (key) {
                            case 'state':
                            case 'downloads':
                            case 'pageViews':
                            case 'projectManagerId':
                            case 'leaderId':
                            case 'verified':
                            case 'verifiedAt':
                            case 'rank':
                                value = editCtrl.data[key];
                                break;
                            case 'projectManager':
                            case 'verifier':
                                value = angular.copy(editCtrl.data[key]);
                                break;
                            default:
                                break;

                        }
                    });
                    editCtrl.original = angular.copy(editData);
                    editCtrl.original.isAssigned = editCtrl.data.isAssigned;
                    editCtrl.original.hasVerified = editCtrl.data.hasVerified;
                }
                break;
            case 'process':
                //负责人选项
                if (!editCtrl.typeOptions) {
                    editCtrl.typeOptions = ['合伙人'];
                }
                //是否委派
                editData.isAssigned = (editData.demand.leader === undefined || editData.demand.leader === null || editData.demand.projectManager === undefined || editData.demand.projectManager === null) ? false : true;
                //判断是否有负责人，有的话设置好，并判断是否与发布者一致
                if (editData.demand.leader) {
                    $rootScope.leaderCandidate = editData.demand.leader.name;
                    $rootScope.leaderCandidateId = editData.demand.leader.id;
                    if (editData.demand.leaderId === editData.demand.publisherId) {
                        editCtrl.type = "申请人";
                        editCtrl.typeOptions[1] = '申请人';
                    } else {
                        editCtrl.type = "合伙人";
                    }
                }
                //判断是否有项目经理，有的话设置好
                if (editData.demand.projectManager) {
                    editCtrl.manager = editData.demand.projectManager.name;
                }
                //将线上数据赋值给显示数据、线上数据、备份数据
                editCtrl.data = angular.copy(editData);
                editCtrl.backup = angular.copy(editData);
                break;
            case 'user':
                var count = 0;
                if (editData.referenceId !== null) {
                    MetaResources.user.get({
                            'id': editData.referenceId
                        },
                        function(data) {
                            $rootScope.referenceCandidate = data.name;
                            $rootScope.referenceCandidateId = editData.referenceId;
                            editCtrl.backupreferenceName = data.name;
                            editCtrl.backupreferenceId = editData.referenceId;
                        },
                        function(error) {
                            MetaRemind.serverError(error);
                        });
                } else {
                    editCtrl.backupreferenceName = '暂无';
                    editCtrl.backupreferenceId = '';
                }
                editData.research = false;
                if (editData.tags !== undefined) {
                    for (var i = 0; i < editData.tags.length; i++) {
                        if (editData.tags[i] === "科研人员") {
                            editData.research = true;
                        }
                    }
                }
                var processKey = {
                    'demand': {
                        query: 'tags_not',
                        method: 'demand'
                    },
                    'technology': {
                        query: 'tags_not',
                        method: 'technology'
                    },
                    'cooperation': {
                        query: 'tags',
                        method: 'demand'
                    },
                    'solution': {
                        query: 'tags',
                        method: 'technology'
                    }
                };
                angular.forEach(processKey, function(innerValue, key) {
                    var queryParams = {
                        '_range': 0,
                        'publisher_id': editData.id,
                        'version': 'online'
                    };
                    queryParams[innerValue.query] = '合作';
                    MetaResources[innerValue.method].query(queryParams,
                        function(data, header) {
                            editData[key] = header()['x-count'];
                            count++;
                            if (count === 4) {
                                editCtrl.data = angular.copy(editData);
                                editCtrl.backup = angular.copy(editData);
                            }
                        },
                        function(error) {
                            MetaRemind.serverError(error);
                        });
                });
                break;
            case "achievementsList":
                editCtrl.data.projects = [];
                editCtrl.data.papers = [];
                editCtrl.data.patents = [];
                for (var i = 0; i < editData.length; i++) {
                    switch (editData[i].tag) {
                        case '项目':
                            editCtrl.data.projects[editCtrl.data.projects.length] = editData[i];
                            break;
                        case '论文':
                            editCtrl.data.papers[editCtrl.data.papers.length] = editData[i];
                            break;
                        case '专利':
                            editCtrl.data.patents[editCtrl.data.patents.length] = editData[i];
                            break;
                    }
                }
                break;
            default:
                editCtrl.data = angular.copy(editData);
                editCtrl.backup = angular.copy(editData);
                break;
        }
    };

    /**
     * @name 保存数据前的预处理
     * @description 与处理多选项、范围值以及调整右边控件区的属性
     */
    metaEdit.setPreProcess = function(editData, editType) {
        //遍历所有属性，预处理多选项、范围值
        angular.forEach(editData, function(value, key) {
            switch (key) {
                case 'areas':
                    editData.areas = [];
                    for (var i = 0; i < MetaConstants.map.areas.length / 2; i++) {
                        if (editData.area_choice[MetaConstants.map.areas[i + MetaConstants.map.areas.length / 2]]) {
                            editData.areas[editData.areas.length] = MetaConstants.map.areas[i];
                        }
                    }
                    break;
                // case 'areas':
                //       var temp = [];
                //       for (var i = 0; i < editData.areas.length; i++) {
                //         temp[i] = editData.areas[i].areaValue;
                //       }
                //       editData.areas = angular.copy(temp);
                //       break;
                case 'coverImg':
                      editData.cover = editData.coverImg.link;
                      break;
                case 'partnerInfo':
                    editData.partnerInfo.areas = [];
                    for (var i = 0; i < MetaConstants.map.areas.length / 2; i++) {
                        if (editData.area_choice[MetaConstants.map.areas[i + MetaConstants.map.areas.length / 2]]) {
                            editData.partnerInfo.areas[editData.partnerInfo.areas.length] = MetaConstants.map.areas[i];
                        }
                    }
                    break;
                case 'cooperationWays':
                    editData.cooperationWays = [];
                    for (var i = 0; i < MetaConstants.map.cooperations.length; i++) {
                        if (editData.cooperationForm_choice[MetaConstants.map.cooperations[i + MetaConstants.map.cooperations.length / 2]]) {
                            editData.cooperationWays[editData.cooperationWays.length] = MetaConstants.map.cooperations[i];
                        }
                    }
                    break;
                case 'willingToFollow':
                case 'proprietary':
                case 'patentState':
                    if (value === "true") {
                        editData[key] = true;
                    } else {
                        editData[key] = false;
                    }
                    break;
                case 'leader':
                    if (editData.leader.partnerInfo === null || editData.leader.partnerInfo === undefined) {
                        editData.leader.partnerInfo = {};
                        editData.leader.partnerInfo.areas = [];
                    } else {
                        editData.leader.partnerInfo.areas = [];
                    }
                    for (var i = 0; i < MetaConstants.map.areas.length / 2; i++) {
                        if (editData.way_choice[MetaConstants.map.areas[i + MetaConstants.map.areas.length / 2]]) {
                            editData.leader.partnerInfo.areas[editData.leader.partnerInfo.areas.length] = MetaConstants.map.areas[i];
                        }
                    }
                    break;
                default:
                    break;
            }
        });
    };

    /**
     * @name 同步数据
     * @description 保存修改之后，将新数据同步到备份数据中，这样重置才能重置到新数据中，如果是需求和技术，则还需要同步到online数据中
     */
    metaEdit.syncData = function(editCtrl, editType) {
        editCtrl.backup = angular.copy(editCtrl.data);
        if (editType === 'demand' || editType === 'technology') {
            editCtrl.online = angular.copy(editCtrl.data);
        }
    };

    /**
     * @name 更改状态
     * @description 更改所有相关的state属性值
     */
    metaEdit.changeState = function(type, id, state) {
        MetaResources[type].save({
            'id': id
        }, {
            'state': state
        });
    };

    return metaEdit;
}]);
